//
//  ScenicStoryListView.swift
//  LeTu
//
//  Created by g1 on 2024/2/4.
//

import UIKit
import BUAdSDK

class ScenicStoryListView: UIView {

    private var classifyItems = [StoryTypeModel]()
    private var listenPermission: Bool
    private var currentPlayStoryModel: ScenicStoryModel
    private var viewModel: ScenicDetailVM
        
    var clickStoryHandle: ((Int, [ScenicStoryModel], Bool) -> Void)?
    
    private var panPositionY: CGFloat = 0
    private var panStartPositionY: CGFloat = 0
    
    // 激励广告
    private var rewardAd: BUNativeExpressRewardedVideoAd?
    
    // 广告播放index
    private var adPlayIndex = -1
    
    init(scenicModel: ScenicModel, currentPlayStoryModel: ScenicStoryModel) {
        self.listenPermission = scenicModel.listenPermission
        self.currentPlayStoryModel = currentPlayStoryModel
        viewModel = ScenicDetailVM(scenicModel: scenicModel)
        super.init(frame: .zero)
        configUI()
        layoutIfNeeded()
        sectionHeader.setList(classifyItems: scenicModel.storyTypeList, index: viewModel.currentClassifysIndex)

    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
        DispatchQueue.main.async {
            self.backView.layerCornerRadius(16, [.topLeft, .topRight])
        }
    }
    func setSectionData(classifyItems: [StoryTypeModel]) {
        self.classifyItems = classifyItems
        sectionHeader.setList(classifyItems: classifyItems, index: viewModel.currentClassifysIndex)
    }
    func setCurrentPlayStoryModel(_ storyModel: ScenicStoryModel) {
        currentPlayStoryModel = storyModel
        storyTableView.reloadData()
    }

    func updateViewInfo(scenicModel: ScenicModel) {
        self.listenPermission = scenicModel.listenPermission
        self.viewModel.update(scenicModel: scenicModel)
        getData(isLoad: true)
    }
    
    func reloadList() {
        sectionHeader.setList(classifyItems: viewModel.scenicModel.storyTypeList, index: viewModel.currentClassifysIndex)
        storyTableView.reloadData()
    }
    
    private func getData(isLoad: Bool) {
        
        if isLoad == false {
            getAllScenics()
            storyTableView.footerResetNoMoreData()
        }
        
        StoryDataManager.shard.getScenics(isLoad: isLoad, currentClassifysIndex: viewModel.currentClassifysIndex) { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            
            DispatchQueue.main.async {
                
                if isLoad {
                    strongSelf.storyTableView.footerEndRefreshing()
                } else {
                    strongSelf.storyTableView.headerEndRefreshing()
                }
                
                guard strongSelf.viewModel.isLoadAllSuccess == false else { 

                    strongSelf.storyTableView.footerEndRefreshingWithNoMoreData()
                    
                    UIView.performWithoutAnimation {
                        strongSelf.storyTableView.reloadData()
                    }
                    return
                }
                
                if dialog.code != 200 {
                    strongSelf.showMessage(message: dialog.message)
                }
                
                if let tempDatas = dialog.data as? [ScenicStoryModel], tempDatas.count == 0 || tempDatas.count % StoryDataManager.shard.pageSize > 0 {
                    strongSelf.storyTableView.footerEndRefreshingWithNoMoreData()
                }
                UIView.performWithoutAnimation {
                    strongSelf.storyTableView.reloadData()
                }
                
            }
            
        }
        
    }
    // 获取全部景点
    private func getAllScenics() {
        
        StoryDataManager.shard.getAllScenics(scenicId: viewModel.scenicModel.id, currentClassifysIndex: viewModel.currentClassifysIndex) { [weak self] dialog in
            
            guard let strongSelf = self, let classifysIndex = dialog.data as? Int else { return }
            
            DispatchQueue.main.async {
                
                // 设置播放器列表
                if AppAudioManager.shared.currentClassifysIndex == classifysIndex {
                    AppAudioManager.shared.setPlayList(StoryDataManager.shard.classifyItems[classifysIndex].sourceArr, currentIndex: AppAudioManager.shared.currentURLIndex, listenPermission: strongSelf.viewModel.scenicModel.listenPermission)
                }
                
                // 结束加载
                strongSelf.storyTableView.footerEndRefreshingWithNoMoreData()
                
                // 更新UI
                UIView.performWithoutAnimation {
                    strongSelf.storyTableView.reloadData()
                }
                
            }
            
        }
        
    }
    private func getListHeight() -> CGFloat {
        return screenHeight-Size.navigationBarHeight - 120
    }
    /// 播放音频
    private func playAudio(index: Int, isForce: Bool = false) {
        guard viewModel.sourceArr.count > 0 else { return }
        let storyModel = viewModel.sourceArr[index]
        guard let handle = clickStoryHandle, viewModel.scenicModel.listenPermission == true || (viewModel.scenicModel.listenPermission == false && storyModel.payStatus == 0) || isForce == true else {
            toPay(index: index)
            return
        }
        currentPlayStoryModel = storyModel
        handle(index, viewModel.sourceArr, isForce)
    }
    private func toPay(index: Int) {
        
        goPayment()
        
//        let lockAlertView = LockScenicAlertView()
//        lockAlertView.clickBuyHandle = { [weak self] in
//            guard let strongSelf = self else { return }
//            strongSelf.goPayment()
//        }
//        lockAlertView.clickCheckAadHandle = { [weak self] in
//            guard let strongSelf = self else { return }
//            strongSelf.adPlayIndex = index
//            strongSelf.getAdData()
//        }
//        lockAlertView.show()
    }
    private func goPayment() {
        guard let currentVC = Utils.getTopVC() else { return }
        if kUserManager.isLogin {
            currentVC.show(PaymentVC(scenicModel: viewModel.scenicModel), sender: nil)
        } else {
            currentVC.showDetailViewController(LoginVC(viewType: .authCode), sender: nil)
        }
    }
    
    // MARK: - configUI
    func configUI() {
        
        addSubview(backView)
        backView.addSubview(storyTableView)
        
        let listHeight = getListHeight()
        backView.snp.makeConstraints { make in
            make.height.equalTo(listHeight)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(listHeight)
        }
        storyTableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        storyTableView.delegate = self
        storyTableView.dataSource = self
        storyTableView.register(cellClass: ScenicDetailStoryTableViewCell.self)
        storyTableView.addRefreshHeaderCallback { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.getData(isLoad: false)
        }
        storyTableView.addRefreshFooterCallback { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.getData(isLoad: true)
        }
        
        sectionHeader.backgroundColor = .white
        
    }
    private lazy var backView = UIView()
    private lazy var sectionHeader = ScenicDetailSectionView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 58))
    private lazy var storyTableView: UITableView = {
        let storyTableView = UITableView()
        storyTableView.tableFooterView = UIView()
        storyTableView.showsVerticalScrollIndicator = false
        return storyTableView
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension ScenicStoryListView: BUNativeExpressRewardedVideoAdDelegate {
    
    // 加载广告信息
    private func getAdData() {
        rewardAd = kAdsManager.loadRewardedTheAdvertising(delegate: self)
        if rewardAd != nil {
            rewardAd?.loadData()
        } else {
            kAdsManager.requestAdsIdList { [weak self] dialog in
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    strongSelf.rewardAd = kAdsManager.loadRewardedTheAdvertising(delegate: strongSelf)
                    strongSelf.rewardAd?.loadData()
                }
            }
        }
        
    }
    
    func nativeExpressRewardedVideoAdDidLoad(_ rewardedVideoAd: BUNativeExpressRewardedVideoAd) {
        
        guard let currentVC = Utils.getTopVC() else { return }
        // 广告加载成功之后，可以调用展示方法，按照实际需要调整代码位置
        rewardedVideoAd.show(fromRootViewController: currentVC)
    }
    
    func nativeExpressRewardedVideoAdDidClose(_ rewardedVideoAd: BUNativeExpressRewardedVideoAd) {
        print("点击了关闭")
        
        guard adPlayIndex != -1 else { return }
        playAudio(index: adPlayIndex, isForce: true)
        
    }
    
    
}

extension ScenicStoryListView: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 58
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return sectionHeader
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.sourceArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(ScenicDetailStoryTableViewCell.self, indexPath: indexPath)
        let stortyModel = viewModel.sourceArr[indexPath.row]
        cell.setStoryModel(stortyModel, index: indexPath.item, isPlaying: stortyModel == currentPlayStoryModel && AppAudioManager.shared.isPlaying == true)
        cell.setListenPermission(listenPermission)
        cell.clickPlayBtnHandle = { [weak self] index, stortyModel in
            guard let strongSelf = self else { return }
            strongSelf.playAudio(index: index)
            strongSelf.storyTableView.reloadData()
        }
        cell.clickLockBtnHandle = { [weak self] index, stortyModel in
            guard let strongSelf = self else { return }
            strongSelf.toPay(index: index)
        }
        cell.clickTryOutBtnHandle = { [weak self] index, stortyModel in
            guard let strongSelf = self else { return }
            strongSelf.playAudio(index: index)
            strongSelf.storyTableView.reloadData()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        playAudio(index: indexPath.row)
        tableView.reloadData()
    }
    
}

extension ScenicStoryListView {
    
    func show() {
        
        isHidden = false
        let tapGR = UITapGestureRecognizer.init(target: self, action: #selector(hide))
        tapGR.delegate = self
        addGestureRecognizer(tapGR)
        
        UIView.animate(withDuration: 0.2, animations: {
            self.backgroundColor = UIColor.black.withAlphaComponent(0.6)
            self.backView.snp.updateConstraints { make in
                make.bottom.equalTo(0)
            }
            self.layoutIfNeeded()
        })

        sectionHeader.repeatHandle = { isOn in
            AppAudioManager.shared.isAutoPlay = isOn
        }
        sectionHeader.selectClassifyHandle = { [weak self] _ , index in
            guard let strongSelf = self else { return }
            strongSelf.viewModel.currentClassifysIndex = index
            strongSelf.getData(isLoad: false)
        }
    }
    
    @objc private func hide(completion: (() -> Void)? = nil) {
        
        self.backView.snp.updateConstraints { make in
            make.bottom.equalTo(self.getListHeight())
        }
        UIView.animate(withDuration: 0.2, animations: {
            self.backgroundColor = UIColor.black.withAlphaComponent(0.0)
            self.layoutIfNeeded()
        }) { finished in
            guard finished else { return }
            DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
                self.isHidden = true
            }
        }
        
    }
    
}

extension ScenicStoryListView: UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        
        if let view = touch.view, view.isDescendant(of: backView) {
            return false
        }
        
        return true
    }
    
    @objc func panGestureRecognizerAction(_ panGR: UIPanGestureRecognizer) {
        
        let position = panGR.location(in: backView)
        var scale = position.y - panPositionY
        
        if panGR.state == .began {
            panPositionY = position.y
        } else if panGR.state == .changed {
            if scale < 0 {
                scale = 0
            }
            
            snp.updateConstraints { make in
                make.bottom.equalTo(scale)
            }
            layoutIfNeeded()
        } else if panGR.state == .ended {
            if scale > 40 {
                hide()
            } else {
                snp.updateConstraints { make in
                    make.bottom.equalTo(0)
                }
            }
        }
        
    }
    
}


